<?php
namespace app\index\controller;

use think\Cache;

class Ajax extends \think\Controller
{


    public function join()//用户加入
    {
        $user_list = cache::get('user_list') ? cache::get('user_list') : array();
        if (!in_array(['uid' => input('username')], $user_list)) {
            array_push($user_list, ['uid' => input('username')]);//插入
            cache::set('user_list', $user_list);
        }
        return $this->user_list();
    }

    public function out()//用户退出
    {
        $user_list = cache::get('user_list');
        if (in_array(['uid' => input('username')], $user_list)) {
            unset($user_list[array_search(['uid' => input('username')], $user_list)]);//删除
            cache::set('user_list', $user_list);
        }
        return $this->user_list();
    }

    public function user_list()//用户列表数据
    {
        $data = cache::get('user_list');
        $this->assign('data', $data);
        $return['user_list'] = $this->fetch('ajax/user_list');
        $return['count'] = count($data);
        return $return;
    }

    public function send()//用户发消息
    {
        $input = input();
        if ($input['msg']) {
            $input['time'] = time();
            $user_mes = cache::get("user_mes") ? cache::get("user_mes") : array();
            array_push($user_mes, $input);//插入
            $res = cache::set('user_mes', $user_mes);
            if ($res) {
                $return['mes'] = "设置成功";
                $return['status'] = 200;
                $return['data'] = $this->send_str($input);
            } else {
                $return['mes'] = "系统繁忙";
                $return['status'] = 404;
            }
        } else {
            $return['mes'] = "请输入消息内容";
            $return['status'] = 404;
        }
        return $return;
    }

    public function send_str($arr)
    {
        return "<div><h3 style='margin-left: 30%;'>".date("m-d H:i:s",$arr['time'])."</h3><span>" . $arr['msg'] . "</span></div>";
    }
}
